package com.ajocer.springbootinit.langchain;

import com.ajocer.springbootinit.manager.SparkClient;
import com.ajocer.springbootinit.manager.constant.SparkApiVersion;
import com.ajocer.springbootinit.manager.model.SparkMessage;
import com.ajocer.springbootinit.manager.model.SparkSyncChatResponse;
import com.ajocer.springbootinit.manager.model.request.SparkRequest;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.output.Response;
import dev.langchain4j.agent.tool.ToolSpecification;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.ajocer.springbootinit.manager.model.MultiModalData;
import com.ajocer.springbootinit.manager.model.ToolSpecificChatLanguageModel;
import com.ajocer.springbootinit.manager.model.MultiModalChatLanguageModel;

/**
 * 讯飞星火聊天模型适配器
 */
@Slf4j
public class XingfengChatModel implements ChatLanguageModel, ToolSpecificChatLanguageModel, MultiModalChatLanguageModel {

    private final SparkClient sparkClient;
    private final double temperature;
    private final int maxTokens;
    private final double presencePenalty;
    private final double frequencyPenalty;

    /**
     * 使用API参数直接创建XingfengChatModel
     * 
     * @param apiHost API主机地址
     * @param appId 应用ID
     * @param apiKey API密钥
     * @param apiSecret API密钥
     */
    public XingfengChatModel(String apiHost, String appId, String apiKey, String apiSecret) {
        SparkClient client = new SparkClient();
        client.appid = appId;
        client.apiKey = apiKey;
        client.apiSecret = apiSecret;
        
        this.sparkClient = client;
        this.temperature = 0.7; // 默认温度
        this.maxTokens = 4096; // 默认最大token数
        this.presencePenalty = 1.0; // X1默认重复惩罚度
        this.frequencyPenalty = 0.02; // X1默认重复词惩罚度
    }
    
    /**
     * 使用SparkClient创建XingfengChatModel
     * 
     * @param sparkClient 星火API客户端
     * @param temperature 温度参数
     * @param maxTokens 最大token数
     */
    public XingfengChatModel(SparkClient sparkClient, double temperature, int maxTokens) {
        this.sparkClient = sparkClient;
        this.temperature = temperature;
        this.maxTokens = maxTokens;
        this.presencePenalty = 1.0; // X1默认重复惩罚度
        this.frequencyPenalty = 0.02; // X1默认重复词惩罚度
    }
    
    /**
     * 使用SparkClient创建XingfengChatModel（完整参数）
     * 
     * @param sparkClient 星火API客户端
     * @param temperature 温度参数
     * @param maxTokens 最大token数
     * @param presencePenalty 重复惩罚度
     * @param frequencyPenalty 重复词惩罚度
     */
    public XingfengChatModel(SparkClient sparkClient, double temperature, int maxTokens, 
                             double presencePenalty, double frequencyPenalty) {
        this.sparkClient = sparkClient;
        this.temperature = temperature;
        this.maxTokens = maxTokens;
        this.presencePenalty = presencePenalty;
        this.frequencyPenalty = frequencyPenalty;
    }

    @Override
    public Response<AiMessage> generate(List<ChatMessage> messages) {
        List<SparkMessage> sparkMessages = convertMessages(messages);
        try {
            SparkRequest request = SparkRequest.builder()
                    .apiVersion(SparkApiVersion.X1) // 使用X1模型
                    .messages(sparkMessages)
                    .temperature(temperature)
                    .maxTokens(maxTokens)
                    .presencePenalty(presencePenalty)
                    .frequencyPenalty(frequencyPenalty)
                    .build();
            SparkSyncChatResponse response = sparkClient.chatSync(request);
            String content = response.getContent();
            AiMessage aiMessage = new AiMessage(content);
            return Response.from(aiMessage);
        } catch (Exception e) {
            log.error("星火API调用失败", e);
            throw new RuntimeException("星火API调用失败: " + e.getMessage(), e);
        }
    }

    @Override
    public Response<AiMessage> generate(List<ChatMessage> messages, ToolSpecification toolSpecification) {
        // 星火API不直接支持单个工具调用，这里简单实现
        log.warn("星火API不直接支持单个工具调用功能，将忽略工具规范");
        return generate(messages);
    }

    @Override
    public Response<AiMessage> generate(List<ChatMessage> messages, List<ToolSpecification> toolSpecifications) {
        // 星火API不直接支持多个工具调用，这里简单实现
        log.warn("星火API不直接支持多个工具调用功能，将忽略工具规范");
        return generate(messages);
    }

    /**
     * 将LangChain4j消息转换为星火消息
     */
    private List<SparkMessage> convertMessages(List<ChatMessage> messages) {
        return messages.stream().map(message -> {
            if (message instanceof UserMessage) {
                return SparkMessage.userContent(message.text());
            } else if (message instanceof AiMessage) {
                return SparkMessage.assistantContent(message.text());
            } else if (message instanceof SystemMessage) {
                return SparkMessage.systemContent(message.text());
            } else {
                throw new UnsupportedOperationException("不支持的消息类型: " + message.getClass().getName());
            }
        }).collect(Collectors.toList());
    }

    @Override
    public Response<AiMessage> generateMultiModal(List<ChatMessage> messages, List<MultiModalData> multiModalData) {
        throw new UnsupportedOperationException("星火API暂不支持多模态输入");
    }
} 